#!/usr/bin/env python
#
# Copyright 2010 Steve Leach
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
#
# This is the main entry point for the application.
# It runs under Google's AppEngine environment
#       http://code.google.com/appengine/
#  
# Currently there is too much going on in this file and a lot of the content
# should be moved into other files.
#

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users

import os
import time
import logging
import random

from datetime import date

from opshandlers import add_ops_mappings	
from eveoperation import EveOperation, Pilot, MultiPay, Corp, update_pilot_last_ops, WaitingPilot
from payments import add_payment_mappings
from sites import add_sites_mappings, get_site_names
from stats import StatsHandler
from scanning import add_scanning_mappings
from evedata import EveData, get_eve_data
from formatting import format_thousands
from awaylist import add_awaylist_mappings
from rest import add_rest_mappings
from closing import add_closing_mappings
from handlers import BaseHandler, EveOpsHandler, SimplePageHandler, add_base_mappings
import pilot_api_info

def is_fc(eve_data, op):
	"""
	Returns true if the current user is the Fleet Commander
	for the specified operation.
	"""
	return eve_data.char_name == op.fc

def get_op(request):
	"""
	Checks the http request params to try and identify which eve operation
	should be used.
	"""
	if request.get('key'):
		op = db.get(request.get('key'))
	elif request.get('id'):
		op = EveOperation.get_by_id(int(request.get('id')))
	return op

def authorised(eve_data, handler):
	"""
	Check if the player is authorised to use the site.
	We need to know who they are and whether they are in an approved corp.
	If they are not authorised, redirect them to an error page.
	Return True if they are authorised, False otherwise.
	"""

	# First check the character name
	if eve_data.char_name == '{unknown}':
		handler.redirect('/unauthorized?reason=id')
		return False

	# Then check to see if the player is in an approved corp
	corp = Corp.gql('WHERE corp_id = :1', eve_data.corp_id)
	if corp.count() > 0:
		corp = corp.get()
	elif eve_data.corp_id:
		corp = Corp(corp_name=eve_data.corp_name)
		corp.corp_id = eve_data.corp_id
		corp.put()

	if not corp.prime:
		handler.redirect('/unauthorized?reason=corp')
		return False

	return True

class UnauthHandler(webapp.RequestHandler):
	def get(self):  	
		logon_url = users.create_login_url('/')
		eve_data = get_eve_data(self.request.headers)

	  	values = {'eve_data': eve_data, 'headers': self.request.headers, 'login_url': logon_url}

  		path = os.path.join(os.path.dirname(__file__), 'unauth.html')
  		self.response.out.write(template.render(path, values))	

class SetStyleHandler(webapp.RequestHandler):
	"""
	Http request handler for changing the user's preferred stylesheet.
	"""
	def get(self):  
		eve_data = get_eve_data(self.request.headers)
		if not authorised(eve_data, self):
			return	

		pilot = Pilot.gql('WHERE char_name = :1', eve_data.char_name).get()
		if pilot:
			pilot.stylesheet = self.request.get('style')
			pilot.put()		

		self.redirect('/')
		
class PilotListHandler(BaseHandler):
	"""
	Http request handler for the pilots list.
	"""
	def do_get(self):  
		pilots = Pilot.all()
		pilots.order('char_name')

		pilot = Pilot.gql('WHERE char_name = :1', self.eve_data.char_name).get()
		
		self.pagevalues['is_super'] = (pilot.is_dev or pilot.is_director)

		#update_pilot_last_ops()
		if self.request.get('force') == 'true':
			self.force_pilot_list()

		self.pagevalues['pilots'] = pilots

	  	self.show_page('altlist.html')

	def do_post(self):
		alt_name = self.request.get('alt_name')
		main_name = self.eve_data.char_name
		pilot = Pilot.gql('WHERE char_name = :1', main_name).get()
		pilot.alts.append(alt_name)
		pilot.put()

		self.set_main(alt_name, main_name)

		self.redirect('/altlist')

	def force_pilot_list(self):
		for pilot in Pilot.all():
			for alt_name in pilot.alts:
				self.set_main(alt_name, pilot.char_name)

	def set_main(self, alt_name, main_name):
		alt = Pilot.gql('WHERE char_name = :1', alt_name).get()
		if not alt:
			alt = Pilot()
			alt.char_name = alt_name
		alt.main_char = main_name
		alt.is_main = False
		alt.put()

class GoogleAccountHandler(BaseHandler):
	def do_get(self):  
	  	self.show_page('setgoogle.html')

	def do_post(self):
		eve_data = get_eve_data(self.request.headers)
		if not authorised(eve_data, self):
			return	

		pilot = Pilot.gql('WHERE char_name = :1', eve_data.char_name).get()
		pilot.google_account = self.request.get('google_account')
		pilot.corp_id = eve_data.corp_id
		pilot.put()
		self.redirect('/altlist')

class SetDirectorHandler(BaseHandler):
	def do_get(self):  
		eve_data = get_eve_data(self.request.headers)
		if not authorised(eve_data, self):
			return	

		pilot = Pilot.gql('WHERE char_name = :1', eve_data.char_name).get()
		if pilot:
			if pilot.is_dev or pilot.is_director:
				director = Pilot.gql('WHERE char_name = :1', self.request.get('name')).get()
				if director:
					director.is_director = not director.is_director
					director.put()
			
		self.redirect('/altlist')

def main():
	mappings = []

	add_ops_mappings(mappings)			# opshandlers.py
	add_base_mappings(mappings)			# handlers.py
	add_sites_mappings(mappings)		# sites.py
	add_scanning_mappings(mappings)		# scanning.py
	add_awaylist_mappings(mappings)		# awaylist.py
	add_payment_mappings(mappings)		# payments.py
	add_rest_mappings(mappings)			# rest.py
	add_closing_mappings(mappings)		# closing.py
	pilot_api_info.add_mappings(mappings)

	mappings.append(('/setstyle', SetStyleHandler))
	mappings.append(('/stats', StatsHandler))
	mappings.append(('/setgoogle', GoogleAccountHandler))
	mappings.append(('/unauthorized', UnauthHandler))
  	mappings.append(('/altlist', PilotListHandler))
  	mappings.append(('/pilots', PilotListHandler))
	mappings.append(('/setdirector', SetDirectorHandler))

  	application = webapp.WSGIApplication(mappings, debug=True)
  	util.run_wsgi_app(application)


if __name__ == '__main__':
	main()

